﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace Bittorrent.Bencode {
    internal class Integer : Object, IEquatable<Integer>
    {   
        /// <summary>
        /// Initializes a new instance of the Integer class.
        /// </summary>
        public Integer() {
        }


        internal Integer(byte[] data) {
            Value = long.Parse(Encoding.UTF8.GetString(data));
        }

        public long Value { get; set; }

        public static bool operator ==(Integer self, int value) {
            return self.Equals(value);
        }

        public static bool operator !=(Integer self, int value) {
            return !self.Equals(value);
        }

        public static bool operator ==(Integer self, long value) {
            return self.Equals(value);
        }

        public static bool operator !=(Integer self, long value) {
            return !self.Equals(value);
        }

        public static bool operator ==(Integer self, Integer value) {
            return self.Equals(value);
        }

        public static bool operator !=(Integer self, Integer value) {
            return !self.Equals(value);
        }

        public override bool Equals(object obj) {
            if (obj == null) {
                return false;
            }

            if (obj is Integer) {
                return Value == ((Integer)obj).Value;
            }

            if (obj is int) {
                return Value == (int)obj;
            }

            if (obj is long) {
                return Value == (long)obj;
            }

            return false;
        }

        public override string ToString() {
            return Value.ToString();
        }

        public override int GetHashCode() {
            return Value.GetHashCode();
        }

        bool IEquatable<Integer>.Equals(Integer other) {
            return Equals(other);
        }

        internal override int ByteSize {
            get { return Encoding.UTF8.GetByteCount(String.Format("i{0}e", Value)); }
        }

        internal override int Encode(byte[] data, int offset) {
            Contract.Requires(data != null);
            Contract.Requires(offset > 0);
            Contract.Requires(offset < data.Length);

            string str = String.Format("i{0}e", Value);
            return Encoding.UTF8.GetBytes(str, 0, str.Length, data, offset);
        }
    }
}